package Controller

import (
	"github.com/gin-gonic/gin"
	"hr-system/Global"
	"hr-system/Model"
	"hr-system/Response"
	"log"
	"net/http"
	"strings"
)

func Login(c *gin.Context) {
	DB := Global.GetDB()
	// 获取参数
	var user Model.User
	c.ShouldBind(&user)
	log.Println(user)
	id := user.Id
	password := user.Password
	// 判断账号是否存在
	var duser Model.Employee
	result := DB.Where("id=?", id).First(&duser)
	if result.RowsAffected == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	// 判断密码是否正确
	if strings.Compare(duser.Password, password) != 0 {
		response.Response(c, http.StatusBadRequest, 400, nil, "密码错误")
		return
	}
	// 发放TOKEN
	token, err := Global.ReleaseToken(duser)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "token发放失败")
		log.Printf("token generate error: %v", err)
		return
	}
	// 返回结果
	re := Model.APIUser{Id: id,Name: duser.Name, EmployeeType: duser.EmployeeType}
	response.Success(c, gin.H{"token": token, "data":re}, "登录成功")
}

func Visual(c *gin.Context)  {
	DB := Global.GetDB()
	var allDepartments []Model.Department
	DB.Find(&allDepartments)
	departmentEmployee := make([]Model.DepartmentEmployee, 0)
	length := len(allDepartments)
	for i := 0; i < length; i++ {
		var count int64
		DB.Model(&Model.Employee{}).Where("department_number=?",
			allDepartments[i].DepartmentNumber).Count(&count)
		departmentEmployee = append(departmentEmployee, Model.DepartmentEmployee{
			Name:  allDepartments[i].DepartmentName,
			Value: int(count),
		})
	}
	response.Success(c, gin.H{"data": departmentEmployee}, "统计完成")
}

func DepartmentInit(c *gin.Context)  {
	DB := Global.GetDB()
	var allDepartments []Model.Department
	DB.Find(&allDepartments)
	dNames := make([]string, 0)
	length := len(allDepartments)
	for i := 0; i < length; i++ {
		dNames = append(dNames, allDepartments[i].DepartmentName)
	}
	response.Success(c, gin.H{"data": dNames}, "初始化完成")
}

func PostInit(c *gin.Context)  {
	dName,_ := c.GetPostForm("department_name")
	DB := Global.GetDB()
	var de Model.Department
	DB.Where("department_name=?",dName).First(&de)
	var posts []Model.Post
	DB.Where("department_number=?",de.DepartmentNumber).Find(&posts)
	postNames := make([]string, 0)
	length := len(posts)
	for i := 0; i < length; i++ {
		postNames = append(postNames, posts[i].PostName)
	}
	response.Success(c, gin.H{"data": postNames}, "初始化完成")
}
